<?php
include('simple_html_dom.php');

function pulisci($col){
        $col = ereg_replace('<h2>' , '' ,$col );
        $col = ereg_replace('</h2>' , '' ,$col );
        $col = ereg_replace('<span>' , '' ,$col );
        $col = ereg_replace('</span.*>' , '' ,$col );
        $col = ereg_replace('<strong>' , '' ,$col);
        $col = ereg_replace('</strong>' , '' ,$col);
        $col = ereg_replace('<br>' , '' ,$col);
        $col = ereg_replace('<br />' , '' ,$col); 
        $col = ereg_replace('</div>' , '' ,$col);
        $col = ereg_replace('<td>' , '' ,$col);
        $col = ereg_replace('</td>' , '' ,$col);
        $col = str_replace("\\/" , '\/' ,$col);
        $col = str_replace('<div class="sottoTitoloScioperi">' , '' ,$col);
        $col = str_replace("\r\n", '' ,$col);
        $col = str_replace(". ." , '.' ,$col);
        $col = str_replace("Clicca qui per il dettaglio", '' ,$col);
        $col = str_replace("\t" , '' ,$col );
        return $col;
}

function ping($host, $port, $timeout) 
{ 
  $tB = microtime(true); 
  $fP = fSockOpen($host, $port, $errno, $errstr, $timeout); 
  if (!$fP) { return "down"; } 
  $tA = microtime(true); 
  return round((($tA - $tB) * 1000), 0)." ms"; 
}

function parser () {
   $json_tab=array(); 
   $json_mese = array ();
   $agg="";
   $html = file_get_html('http://www.fsnews.it/cms/v/index.jsp?vgnextoid=d3b868ae9d50a110VgnVCM10000080a3e90aRCRD');   
   foreach ($html->find('div.cboxMese') as $row) { 
       foreach ($row->find('h4.titoloblackboldmed') as $mese) {       
         array_push($json_mese,pulisci($mese->plaintext));
       }
       $json_linea=array(); 
       foreach ($row->find('table.table1') as $table) {
               $json_linea=array();       
               foreach ($table->find('tr') as $linea) {
                  if (pulisci($linea->find('td',0)->plaintext)!="")
            
                     array_push($json_linea,array(
                               'data'=>pulisci($linea->find('td',0)->plaintext),
                               'linea'=>pulisci(urlencode($linea->find('td',1)->plaintext)),
                               'Intervento'=>pulisci(urlencode($linea->find('td',2)->plaintext))
                               ));                   
               }
       array_push($json_tab,$json_linea);
       }       
   }
  $json=array(
   'stato'=>'0',
   'mese'=>$json_mese,
   'table'=>$json_tab
   );
  
  $myFile = "newsTrenitalia.txt";
  $fh = fopen($myFile, 'w');
  $stringData = json_encode($json);
  fwrite($fh, $stringData);
  fclose($fh);
return json_encode($json);
}

ping("www.fsnews.it",80,10);

echo parser();


?>        